from genericpath import getsize
from cryptography.fernet import Fernet
from django.http import HttpResponse, QueryDict
from django.shortcuts import get_object_or_404
from django.utils import timezone
from rest_framework import viewsets
from rest_framework.response import Response

from ImageModule.models import Imagefile, Videofile
from ImageModule.serializers import ImagefileSerializer, VideofileSerializer
from ImageModule.utils.crypt import EncryptedFileField, get_encryption_key
from ImageModule.utils.customstorage import CustomStorage
from SystemConfiguration.models import VideoPath
from airport_logistics_backend import settings

from django.core.files.uploadedfile import TemporaryUploadedFile
from django.core.files.uploadedfile import UploadedFile
import tempfile
import os


class ImageViewSet(viewsets.ModelViewSet):
    # 用一个视图集替代ArticleList和ArticleDetail两个视图
    queryset = Imagefile.objects.all()
    serializer_class = ImagefileSerializer

    # POST 
    def create(self, request):
        serializer = ImagefileSerializer(data=request.data)
        if serializer.is_valid():
            instance = serializer.save()
            # custom_response = {'data': ImagefileSerializer(instance).data, 'message': 'Custom create response'}
            a = ImagefileSerializer(instance)
            # return Response(ImagefileSerializer(instance).data)
            return Response({'message': '新建图片成功'}, status=200)
        return Response(serializer.errors, status=400)

    # GET
    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        print(serializer)
        return Response(serializer.data, status=200)

    def get_queryset(self):
        queryset = Imagefile.objects.all()
        name = self.request.query_params.get('name')
        date = self.request.query_params.get('date')
        type = self.request.query_params.get('type')

        if name:
            queryset = queryset.filter(name__icontains=name)
        if date:
            queryset = queryset.filter(date=date)
        if type:
            queryset = queryset.filter(type__icontains=type)

        return queryset


class VideoViewSet(viewsets.ModelViewSet):
    queryset = Videofile.objects.all()
    serializer_class = VideofileSerializer

    # POST 
    def create(self, request):
        # uploadData = timezone.now().strftime('%Y-%m-%d %H:%M:%S')
        # request.data['upload_date'] = uploadData
        # print(settings.DEFINE_PATH)
        # print(settings.BASE_DIR)
        settings.CUSTOM_STORAGE_LOCATION = VideoPath.objects.order_by('-id').first().path
        storage = CustomStorage(location=settings.CUSTOM_STORAGE_LOCATION, base_url='')
        storage.set_location(new_location=settings.CUSTOM_STORAGE_LOCATION)
        # print(settings.MEDIA_ROOT)
        request.data['size'] = request.FILES['video'].size
        request.data['media_root'] = settings.CUSTOM_STORAGE_LOCATION
        serializer = VideofileSerializer(data=request.data)
        # storage = CustomStorage(location = settings.CUSTOM_STORAGE_LOCATION,base_url='')
        if serializer.is_valid():
            instance = serializer.save()
            return Response({'message': '新建视频成功'}, status=200)
        return Response(serializer.errors, status=400)

    def createByrealtime(self, name, file_path, now_time):
        # 假数据
        # name = 'test'
        # file_path = '/Users/edmond/Workplace/Airport_logistics/测试/视频/过机视频3.mp4'

        # 创建一个临时文件上传
        temp = tempfile.NamedTemporaryFile(delete=False)
        settings.CUSTOM_STORAGE_LOCATION = VideoPath.objects.order_by('-id').first().path
        storage = CustomStorage(location=settings.CUSTOM_STORAGE_LOCATION, base_url='')
        storage.set_location(new_location=settings.CUSTOM_STORAGE_LOCATION)

        with open(file_path, 'rb') as file:  # 打开文件用于二进制读取
            # video_data = file.read()  # 读取文件内容到变量
            video_content = UploadedFile(file,
                                         name=file_path,
                                         content_type='video/mp4',
                                         size=getsize(file_path),
                                         charset='utf-8')

            data = QueryDict(mutable=True)
            uploadData = now_time.strftime('%Y-%m-%d %H:%M:%S')
            data['upload_date'] = uploadData
            data['video'] = video_content
            data['name'] = name
            data['media_root'] = settings.CUSTOM_STORAGE_LOCATION
            # data['size'] = request.FILES['video'].size
            serializer = VideofileSerializer(data=data)
            if serializer.is_valid():
                instance = serializer.save()
                return Response({'message': '新建视频成功'}, status=200)
            else:
                # 数据验证失败，打印错误信息
                print("Validation failed:", serializer.errors)

                # 可以进一步处理错误信息，例如：
                for field, errors in serializer.errors.items():
                    for error in errors:
                        print(f"Error in field '{field}': {error}")

        return Response(serializer.errors, status=400)

    # GET
    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        print(serializer)
        return Response(serializer.data, status=200)

    def get_queryset(self):
        queryset = Videofile.objects.all()
        name = self.request.query_params.get('name')
        startDate = self.request.query_params.get('startDate')
        endDate = self.request.query_params.get('endDate')

        if name:
            queryset = queryset.filter(name__icontains=name)
        if startDate:
            queryset = queryset.filter(upload_date__gte=startDate)
            queryset = queryset.filter(upload_date__lt=endDate)

        return queryset

    # DELETE
    def destroy(self, request, pk=None):
        pk = self.request.query_params.get('id')
        video = get_object_or_404(Videofile, pk=pk)
        video.delete()
        return Response({'message': '视频删除成功'}, status=200)


def download_image(request):
    cipher_suite = Fernet(EncryptedFileField.get_encryption_key())

    encrypted_file_path = request.GET['url']
    encrypted_file_path = settings.MEDIA_ROOT + '/' + encrypted_file_path
    with open(encrypted_file_path, 'rb') as encrypted_file:
        encrypted_content = encrypted_file.read()
        decrypted_content = cipher_suite.decrypt(encrypted_content)

    # 设置响应头
    response = HttpResponse(content_type='image/png')
    response['Content-Disposition'] = 'attachment; filename="image.png"'

    # 设置响应内容
    response.write(decrypted_content)

    return response


def download_video(request):
    cipher_suite = Fernet(get_encryption_key())

    encrypted_file_path = request.GET['url']
    encrypted_file_path = encrypted_file_path.split('videos/')[1]
    encrypted_file_path = request.GET['media_root'] + '/videos/' + encrypted_file_path
    with open(encrypted_file_path, 'rb') as encrypted_file:
        encrypted_content = encrypted_file.read()
        decrypted_content = cipher_suite.decrypt(encrypted_content)

    # 设置响应头
    response = HttpResponse(content_type='video/mp4', status=200)
    response['Content-Disposition'] = 'attachment; filename="video.mp4"'

    # 设置响应内容
    response.write(decrypted_content)

    return response
